<div class="row">
    <div class="col-md-12 widget-module">
        <div class="box-widget">
            <form id="salesinvoice" method="post" class="form-horizontal form-box">
            <table id="list-group" class="table data-tbl-boxy responsive">
                <thead>
                    <tr>
                        <th>#</th>
                        <th><?php echo $this->translate('product name'); ?></th>
                        <th><?php echo $this->translate('net'); ?></th>
                        <th><?php echo $this->translate('brand'); ?></th>
                        <th><?php echo $this->translate('price'); ?></th>
                        <!--<th><?php echo $this->translate('discount value'); ?></th>
                        <th><?php echo $this->translate('discount type'); ?></th>-->
                        <th><?php echo $this->translate('quantity'); ?></th>
                        <th><?php echo $this->translate('total price'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php $i = 0; ?>
                    <?php foreach($this->products as $product): ?>
                    <?php $i++; ?>
                    <tr id="product">
                        <td id="stt">
                            <?php echo $i; ?>
                        </td>
                        <td id="name">
                            <input type="checkbox" name="check" value="1" id="checkToDelete" />
                            <?php echo $product['name']; ?> <br />
                            <!--<a class="btn btn-mini btn-danger" id="deleteForAllCustomer">Xóa tất cả</a>--> <a class="btn btn-mini btn-danger" id="deleteForThisCustomer">Xóa</a>
                        </td>
                        <td id="net">
                            <?php echo $product['net']; ?>
                        </td>
                        <td id="brand">
                            <?php echo $product['brand']; ?>
                        </td>
                        <td id="price">
                            <?php
                                if(isset($product['price'])){
                                    $price = $product['price'];
                                }else{
                                    $price = $product['s_price'];
                                }
                                
                                $discount = 0;
                                
                                if($this->customer['discount_type'] == 0){
                                    $discount = $this->customer['discount_value'];
                                }
                                
                                if(isset($product['discount_value'])){
                                    $discount = $product['discount_value'];
                                }
                            ?>
                            <label id="text_price[<?php echo $product['id']; ?>][price]" style="text-align: left;"><?php echo $price; ?></label><br />
                            <input type="hidden" name="product[<?php echo $product['id']; ?>][price]" id="price" value="<?php echo $price; ?>" />
                            <a class="btn btn-mini btn-info" id="changePrice">Sửa</a>
                        </td>
                        <!--<td id="discount">
                            <label id="text_discount[<?php echo $product['id']; ?>][discount]"><?php echo $discount; ?></label><br />
                            <a class="btn btn-mini btn-info" id="changeDiscount">Sửa</a>
                            <input id="discount" type="hidden" value="<?php echo $discount; ?>" name="product[<?php echo $product['id']; ?>][discount]" />
                        </td>
                        <td id="discount_type">
                            <?php 
                                if(!isset($product['discount_type']) || ($product['discount_type'] == 1)){
                                    $discount_type_text = "%";
                                    $discount_type = 1;
                                }else{
                                    $discount_type_text = "VNĐ";
                                    $discount_type = 0;
                                }
                            ?>
                            <label id="text_discount_type[<?php echo $product['id']; ?>][discount_type]"><?php echo $discount_type_text; ?></label><br />
                            <a class="btn btn-mini btn-info" id="changeDiscountType" >Sửa</a>
                            <input id="discount_type" type="hidden" value="<?php echo $discount_type; ?>" name="product[<?php echo $product['id']; ?>][discount_type]" />
                        </td>-->
                        <td id="quantity">
                            <?php
                                $quantity = 0;
                                
                                /*foreach($this->old_order['products'] as $row){
                                    if($row['product_id'] == $product['id']){
                                        $quantity = $row['quantity'];
                                    }
                                }*/
                            ?>
                            <input class="form-control" type="text" value="<?php echo $quantity; ?>" id="quantity" />
                            <input type="hidden" value="<?php echo $quantity; ?>" name="product[<?php echo $product['id']; ?>][quantity]" />
                        </td>
                        <td id="total">
                            <input readonly="" class="form-control" type="text" value="0" class="form-control" id="text_total[<?php echo $product['id']; ?>][total]" />
                            <input type="hidden" id="total" value="0" name="product[<?php echo $product['id']; ?>][total]" />
                            <input type="hidden" name="product[<?php echo $product['id']; ?>][id]" id="id" value="<?php echo $product['id']; ?>" />
                            <!--<input id="discount" type="hidden" value="<?php echo $discount; ?>" name="product[<?php echo $product['id']; ?>][discount]" />
                            <input id="discount_type" type="hidden" value="<?php echo $discount_type; ?>" name="product[<?php echo $product['id']; ?>][discount_type]" />-->
                            <?php echo $this->messageError[$product['id']]['price']; ?>
                            <?php echo $this->messageError[$product['id']]['discount']; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <div id="pageChange" class="form-group">
                <div class="col-lg-3">
                    Đi đến trang: 
                    <select id="gotoPage" size="1">
                        
                    </select>
                </div>
            </div>
            
            <div class="form-group">
                <div class="col-lg-2">
                    <button id="addProduct" type="button" class="btn btn-info">
                        Thêm sản phẩm
                    </button>
                </div>
                
                <div class="col-lg-2">
                    <button id="deleteSelected" type="button" class="btn btn-danger">
                        Xóa mục đã chọn
                    </button>
                </div>
                
                <!--<div class="col-lg-2">
                    <button id="updateDiscount" type="button" class="btn btn-info">
                        Chiết khấu
                    </button>
                </div>-->
            </div>
            
            <div class="form-group">
                <label class="col-lg-9 control-label"><?php echo $this->translate('Giá chưa chiết khấu'); ?></label>
                <div class="col-lg-3">
                    <input readonly="" type="text" class="form-control" id="totalprice" value="0" />
                    <input type="hidden" name="totalprice" value="0" />
                </div>
            </div>
            
            <?php
                if(isset($this->old_order)){
                    $discount = $this->old_order['order']['discount'];
                }
            ?>
            
            <div class="form-group">
                <label class="col-lg-9 control-label"><?php echo $this->translate('Chiết khấu'); ?></label>
                <div class="col-lg-3">
                    <input type="text" class="form-control" id="discount" value="0" />
                    <input type="hidden" name="discount" value="0" />
                </div>
            </div>
            
            <div class="form-group">
                <label class="col-lg-9 control-label"><?php echo $this->translate('subtotal'); ?></label>
                <div class="col-lg-3">
                    <input readonly="" type="text" class="form-control" id="subtotal" value="0" />
                    <input type="hidden" name="subtotal" value="0" />
                </div>
            </div>
            
            <?php
                $dept = $this->dept;
                $payment = $this->payment;
                $order = $this->order;
                $refund = $this->refund;
                $customer_total = current($this->customer_total);
                
                $totalDept = $dept->dept + $order->subtotal - $order->totalpay - $payment->total - $refund->total;
                
                if(isset($customer_total->total)){
                    $totalDept += $customer_total->total;
                }
                
                $old_refund = 0;
                if(isset($this->old_order)){
                    $totalDept -= $this->old_order['order']['subtotal'];
                    $totalDept += $this->old_order['order']['totalpay'];
                }
                
                $totalDept += $this->old_refund;
            ?>
            
            <div class="form-group">
                <label class="col-lg-9 control-label"><?php echo $this->translate('dept'); ?></label>
                <div class="col-lg-3">
                    <input readonly="" type="text" class="form-control" id="dept" value="" />
                    <input type="hidden" name="dept" value="<?php echo $totalDept; ?>" />
                </div>
            </div>
            
            <div class="form-group">
                <label class="col-lg-9 control-label"><?php echo $this->translate('totalpay'); ?></label>
                <div class="col-lg-3">
                    <input type="text" class="form-control" id="totalpay" value="0" />
                    <input type="hidden" name="totalpay" value="0" />
                </div>
            </div>
            
            <div class="form-group">
                <label class="col-lg-9 control-label"><?php echo $this->translate('Trả hàng'); ?></label>
                <div class="col-lg-3">
                    <input type="text" class="form-control" id="refund" value="0" />
                    <input type="hidden" name="refund" value="0" />
                </div>
            </div>
            
            <div class="form-group">
                <label class="col-lg-9 control-label"><?php echo $this->translate('remaining'); ?></label>
                <div class="col-lg-3">
                    <input readonly="" type="text" class="form-control" id="remaining" value="0" />
                    <input type="hidden" name="remaining" value="0" />
                </div>
            </div> 
            
            <div class="form-group">
                <label class="col-lg-4 control-label">&nbsp;</label>
                <div class="col-lg-4">
                    <div id="form-actions" class="form-actions">
                        <button id="submit" onclick="submit()" type="submit" class="btn btn-primary">
                            <i class="icon-save"></i>
                            <?php echo $this->translate('save'); ?>
                        </button>
                        <button id="cancel" type="button" class="btn">
                            <i class="icon-cancel-circle-2"></i>
                            <?php echo $this->translate('cancel'); ?>
                        </button>
                    </div>
                </div>
            </div> 
            <input type="hidden" name="customer_id" value="<?php echo $this->customer_id; ?>" />
            <input type="hidden" name="save" value="1" />
            <?php if(isset($this->old_order)): ?>
                <input type="hidden" name="id" value="<?php echo $this->old_order['order']['id']; ?>" />
            <?php endif; ?>
            </form>
        </div>
    </div>
</div>
<div id="goSubmit">
<a href="#form-actions" class="tip-top" title="Go Top">
    <i class="icon-arrow-down"></i>
</a>
</div>
<div id="add-product-form" title="Thêm sản phẩm">
    <form id="add-product">
        <span id="product-error" style="color: red;">
        
        </span>
        <br />
        Tên sản phẩm<br />
        <input type="text" name="name" value="" /><br />
        
        Net<br />
        <input type="text" name="net" value="" /><br />
        
        Loại sản phẩm<br />
        <input type="text" name="type" value="" /><br />
        
        Thương hiệu<br />
        <select name="brand">
            <option value="0">-- Chọn --</option>
            <?php foreach($this->brands as $row): ?>
                <option value="<?php echo $row->id; ?>"><?php echo $row->brand; ?></option>
            <?php endforeach; ?>
        </select><br />
        
        <input type="hidden" name="customer" value="<?php echo $this->customer_id; ?>" />
        <input type="hidden" name="supplier" value="0" />
        <input type="hidden" name="showinsale" value="1" />
        
        Giá<br />
        <input id="newProductPrice" type="text" name="price" value="" /><br />
        <input type="hidden" name="sale" value="1" />
    </form>
</div>
<script>
var optionNumeric1 = {'aSep': '.', 'aDec': ',', 'mDec': 0, 'vMin': 0, 'vMax': 99999999999, 'wEmpty': 'zero'};
var optionNumeric2 = {'aSep': '.', 'aDec': ',', 'mDec': 0, 'vMin': -99999999999, 'vMax': 99999999999};
var optionNumeric3 = {'aSep': '.', 'aDec': ',', 'mDec': 0, 'vMin': 0, 'vMax': 100, 'wEmpty': 'zero'};

$(document).ready(function(){
    $(window).scroll(function(){
        var scrollTop = $(window).scrollTop();
        
        if(scrollTop > 10){
            $("div.page-header").parent("div.col-md-12").parent("div.row").addClass("fixed");
        }else{
            $("div.page-header").parent("div.col-md-12").parent("div.row").removeClass("fixed");
        }    
    });
    
    <?php if(isset($this->orderID) && $this->orderID > 0): ?>
        window.open('<?php echo $this->url(array('module' => 'default', 'controller' => 'sales-invoice', 'action' => 'view', 'order_id' => $this->orderID), null, true); ?>', 'Chi tiết', 'scrollbars=1,width=1024,height=768');
        window.location.href = "<?php echo $this->url(array('module' => 'default', 'controller' => 'sales-invoice', 'action' => 'manage'), null, true); ?>"; 
    <?php endif; ?>
    
    var i = <?php echo $i; ?>;
    
    $("input#subtotal, input#totalprice, input#dept, input#totalpay, input#refund, input#newProductPrice").autoNumeric('init', optionNumeric1);
    $("input#remaining").autoNumeric('init', optionNumeric2);
    $("input#discount").autoNumeric('init', optionNumeric3);
    
    $("input#dept").autoNumeric('set', <?php echo $totalDept; ?>);
    
    $("input#totalpay").change(function(){
        var totalpay = $(this).autoNumeric('get');
        
        $("input[name='totalpay']").val(totalpay);
        
        remaining();
    });
    
    $("input#refund").change(function(){
        var refund = $(this).autoNumeric('get');
        
        $("input[name='refund']").val(refund);
        
        remaining();
    });
    
    var table = $('#list-group').dataTable({
        "aLengthMenu": [
            [10, 20, 50, 100, -1],
            [10, 20, 50, 100, "All"]
        ],
        "fnDrawCallback": function(){
            $(window).scrollTop(0);
            createGotoPage();
            getCurrentPage();            
        },
        "language": {
            "lengthMenu": "Hiển thị _MENU_ dòng mỗi trang",
            "zeroRecords": "Không có dữ liệu",
            "info": "Trang: _PAGE_ / _PAGES_",
            "infoEmpty": "Không có dữ liệu",
            "infoFiltered": "(Tổng cộng _MAX_ sản phẩm)",
            "search": "Tìm kiếm",
            "paginate": {"next": "Trang sau", "previous": "Trang trước"}
        }
    });
    
    var rows = table.fnGetNodes();
    
    var html = '<br /><br />';
    html += '<button class="btn btn-mini btn-info" type="button" id="selectAll">Chọn tất cả</button> ';
    html += '<button class="btn btn-mini btn-info" type="button" id="selectPrice">Chọn giá = 0</button> ';
    html += '<button class="btn btn-mini btn-info" type="button" id="deselect">Bỏ chọn</button>';
    
    $("#list-group_info").after(html);
    
    $("#selectAll").click(function(){
        var curRow = table.fnGetNodes();
        
        $(curRow).each(function(){
            $(this).children("td#name").children("input#checkToDelete").attr("checked", "checked");
            $(this).children("td#name").children("input#checkToDelete").prop("checked", true);
        });
    });
    
    $("#selectPrice").click(function(){
        var curRow = table.fnGetNodes();
        
        $(curRow).each(function(){
            var price = $(this).children("td#price").children("input#price").val();
            
            $(this).children("td#name").children("input#checkToDelete").removeAttr("checked");
            $(this).children("td#name").children("input#checkToDelete").prop("checked", false);
            
            if(price == 0){
                $(this).children("td#name").children("input#checkToDelete").attr("checked", "checked");
                $(this).children("td#name").children("input#checkToDelete").prop("checked", true);
            }
        });
    });
    
    $("#deselect").click(function(){
        var curRow = table.fnGetNodes();
        
        $(curRow).each(function(){
            $(this).children("td#name").children("input#checkToDelete").removeAttr("checked");
            $(this).children("td#name").children("input#checkToDelete").prop("checked", false);
        });
    });
    
    function getCurrentPage(){
        var t = $("#list-group").DataTable();
        var info = t.page.info();
        var page = info.page;
        page = page + 1;
       
       $("select#gotoPage option").removeAttr("selected");
       $("select#gotoPage option").prop("selected", false);
       
       $("select#gotoPage option[value='" + page + "']").attr("selected", "selected");
       $("select#gotoPage option[value='" + page + "']").prop("selected", true);
    }
    
    $(rows).each(function(){
        var row = $(this);
        
        $(this).children("td#quantity").children("input#quantity").autoNumeric('init', optionNumeric1);
        $(this).children("td#price").children("label[id^='text_price']").autoNumeric('init', optionNumeric1);
        $(this).children("td#discount").children("label[id^='text_discount']").autoNumeric('init', optionNumeric1);
        $(this).children("td#total").children("input[id^='text_total']").autoNumeric('init', optionNumeric1);
        
        var id = $(this).children("td#total").children("input#id").val();
        var price = $(this).children("td#price").children("input#price").val();
        
        $(this).children("td#price").children("label[id^='text_price']").autoNumeric('set', price);
        
        $(this).children("td#name").children("a#deleteForAllCustomer").click(function(){
            deleteForAllCustomer(row);
        });
        
        $(this).children("td#name").children("a#deleteForThisCustomer").click(function(){
            deleteForThisCustomer(row);
            
        });
        
        $(this).children("td#price").children("a#changePrice").click(function(){
            changePrice(row);
        });
        
        $(this).children("td#discount").children("a#changeDiscount").click(function(){
            changeDiscount(row);
        });
        
        $(this).children("td#discount_type").children("a#changeDiscountType").click(function(){
            changeDiscountType(row);
        });
        
        $(this).children("td#quantity").children("input#quantity").change(function(){
            var quantity = $(this).autoNumeric('get');
            
            $(this).parent("td#quantity").children("input[name^='product']").val(quantity);
            
            productTotal(row);
        });
        
        $(this).mouseover(function(){
            $(this).addClass("hover");
        });
        
        $(this).mouseout(function(){
            $(this).removeClass("hover");
        });
        
        <?php
            if(isset($this->old_order)){
                foreach($this->old_order['products'] as $row){
                    //$discount_type = "%";
                    
                    //if($row['discount_type'] == 0){
//                        $discount_type = "VNĐ";
//                    }
                    ?>
                    var curId = <?php echo $row['product_id']; ?>;
                    
                    if(curId == id){
                        var quantity = <?php echo $row['quantity']; ?>;
                        //var discount = <?php echo $row['discount']; ?>;
                        //var discount_type = <?php echo $row['discount_type']; ?>;
                        
                        //$(this).children("td#discount").children("label[id^='text_discount']").autoNumeric('set', discount);
                        //$(this).children("td#discount").children("input#discount").val(discount);
                        
                        //$(this).children("td#discount_type").children("label[id^='text_discount_type']").text("<?php echo $discount_type ?>");
                        //$(this).children("td#discount_type").children("input#discount_type").val(discount_type);
                        
                        $(this).children("td#quantity").children("input#quantity").autoNumeric('set', quantity);
                        $(this).children("td#quantity").children("input[name='product[" + id + "][quantity]']").val(quantity);
                        productTotal(this);
                    }
                    <?php
                }
                ?>
                $("input#discount").autoNumeric('set', <?php echo $this->old_order['order']['discount']; ?>);
                $("input[name='discount']").val(<?php echo $this->old_order['order']['discount']; ?>);
                
                $("input#refund").autoNumeric('set', <?php echo $this->old_refund; ?>);
                $("input[name='refund']").val(<?php echo $this->old_refund; ?>);
                
                $("input#totalpay").autoNumeric('set', <?php echo $this->old_order['order']['totalpay']; ?>);
                $("input[name='totalpay']").val(<?php echo $this->old_order['order']['totalpay']; ?>);
                <?php
            }
        ?>
    });
    
    remaining();
    
    function deleteForAllCustomer(row){
        var ok = confirm("Bạn muốn xóa sản phẩm này?");
        var page = $("div#list-group_paginate ul.pagination li.active a").text();
        
        if(ok){
            var pid = $(row).children("td#total").children("input#id").val();
            
            $.ajax({
                url: "<?php echo $this->url(array('controller' => 'product-buy', 'action' => 'delete-for-all-customer')); ?>",
                type: "POST",
                data: {'id': pid},
                beforeSend: ajaxLoading(),
                success: function(e){
                    $(row).children("td#quantity").children("input[name^='product']").val(0);
                    productTotal(row);
                    var curRow = $(row).closest('tr');
                    table.fnDeleteRow(curRow);
                    totalPrice();
                    remaining();
                    $("div.imgLoading").remove();
                    
                    table.fnPageChange(parseInt(page));
                }
            });
        }
    }
    
    function deleteForThisCustomer(row){
        var ok = confirm("Bạn muốn xóa sản phẩm này?");
        var page = $("div#list-group_paginate ul.pagination li.active a").text();
                    
        if(ok){
            var pid = $(row).children("td#total").children("input#id").val();
            
            $.ajax({
                url: "<?php echo $this->url(array('controller' => 'product-buy', 'action' => 'delete-for-customer')); ?>",
                type: "POST",
                data: {'pid': pid, 'customer_id': <?php echo $this->customer_id; ?>},
                beforeSend: ajaxLoading(),
                success: function(e){
                    $(row).children("td#quantity").children("input[name^='product']").val(0);
                    productTotal(row);
                    var curRow = $(row).closest('tr');
                    table.fnDeleteRow(curRow);
                    totalPrice();
                    remaining();
                    $("div.imgLoading").remove();
                    
                    table.fnPageChange(parseInt(page) - 1);
                }
            });
        }
    }
    
    $("button#deleteSelected").click(function(){
        var ok = confirm("Bạn muốn xóa các sản phẩm đã chọn?");
        var page = $("div#list-group_paginate ul.pagination li.active a").text();
        
        if(ok){
            var i = 0;
            var curRows = table.fnGetNodes();
            var l = $(curRows).length;
            var index = l - 1;
            var lastProduct = $(curRows[index]).children("td#total").children("input#id").val();
            ajaxLoading();
            
            $(curRows).each(function(){
                var checked = $(this).children("td#name").children("input#checkToDelete").prop('checked');
                //i ++;
                if(checked){
                    var pid = $(this).children("td#total").children("input#id").val();
                    var row = $(this);
                    
                    $.ajax({
                        url: "<?php echo $this->url(array('controller' => 'product-buy', 'action' => 'delete-for-customer')); ?>",
                        type: "POST",
                        data: {'pid': pid, 'customer_id': <?php echo $this->customer_id; ?>},
                        success: function(e){
                            $(this).children("td#quantity").children("input[name^='product']").val(0);
                            productTotal(this);
                            var curRow = $(row).closest('tr');
                            table.fnDeleteRow(curRow, false);
                            totalPrice();
                            remaining();
                            
                            $("div.imgLoading").remove();
                        }
                    });
                }
            });
        }
        
        table.fnPageChange(parseInt(page) - 1);
    });
    
    function changePrice(row){
        var data = prompt("Nhập giá tiền");
        
        if(isNaN(data) || data < 0){
            alert("Giá tiền phải là số và lớn hơn hoặc bằng 0");
            return;
        }else{
            $(row).children("td#price").children("label[id^='text_price']").autoNumeric('set', data);
            $(row).children("td#price").children("input#price").val(data);
            
            updatePrice(row);
        }
    }
    
    function changeDiscount(row){
        var data = prompt("Nhập chiết khấu");
        
        if(isNaN(data) || data < 0){
            alert("Chiết khấu phải là số và lớn hơn hoặc bằng 0");
            return;
        }else{
            $(row).children("td#discount").children("label[id^='text_discount']").autoNumeric('set', data);
            $(row).children("td#discount").children("input#discount").val(data);
            
            updatePrice(row);
        }
    }
    
    function changeDiscountType(row){
        var curType = $(row).children("td#discount_type").children("input#discount_type").val();
        var type = 1;
        var text = "%";
        
        if(curType == 1){
            type = 0;
            text = "VNĐ";
        }
        
        $(row).children("td#discount_type").children("label[id^='text_discount_type']").text(text);
        $(row).children("td#discount_type").children("input#discount_type").val(type);
        
        updatePrice(row);
    }
    
    function updatePrice(row){
        var pid = $(row).children("td#total").children("input#id").val();
        var customer_id = <?php echo $this->customer_id; ?>;
        var price = $(row).children("td#price").children("input#price").val();
        var discount = 0;//$(row).children("td#discount").children("input#discount").val();
        var discount_type = 1;//$(row).children("td#discount_type").children("input#discount_type").val();
        
        $.ajax({
            url: "<?php echo $this->url(array('controller' => 'product-price', 'action' => 'update-price')) ?>",
            data: {'pid': pid, 'customer_id': customer_id, 'price': price, 'discount': discount, 'discount_type': discount_type},
            beforeSend: ajaxLoading(),
            success: function(e){
                productTotal(row);
                $("div.imgLoading").remove();
            }
        });
    }
    
    function ajaxLoading(){
        var html = '<div class="imgLoading">';
        html += '<img class="imgLoading" src="<?php echo $this->templateURL; ?>/images/ajax-loader/ajax-loader_orange.gif" />';
        html += '</div>';
        
        $("body").append(html);
    }
    
    function productTotal(row){
        var total = 0;
        var id = $(row).children("td#total").children("input#id").val();
        var price = $(row).children("td#price").children("input#price").val();
        //var discount = $(row).children("td#discount").children("input#discount").val();
        //var discount_type = $(row).children("td#discount_type").children("input#discount_type").val();
        var quantity = $(row).children("td#quantity").children("input[name='product[" + id + "][quantity]']").val();
        
        price = parseFloat(price);
        //discount = parseFloat(discount);
        //discount_type = parseFloat(discount_type);
        quantity = parseFloat(quantity);
        
        /*if(discount_type == 1){
            total = (price * (1 - (discount / 100))) * quantity;
        }else{
            total = (price - discount) * quantity;
        }*/
        
        total = price * quantity;
        
        $(row).children("td#total").children("input#total").val(total);
        $(row).children("td#total").children("input[id^='text_total']").autoNumeric('set', total);
        
        totalPrice();
    }
    
    function totalPrice(){
        var totalprice = 0;
        
        var tRows = table.fnGetNodes();
        
        $(tRows).each(function(){
            var total = $(this).children("td#total").children("input#total").val();
            
            totalprice += parseInt(total);
        });
        
        $("input#totalprice").autoNumeric('set', totalprice);
        $("input[name='totalprice']").val(totalprice);
        
        subTotal();
        remaining();
    }
    
    $("input#discount").change(function(){
        var discount = $("input#discount").autoNumeric('get');
        $("input[name='discount']").val(discount);
        
        subTotal();
        remaining();
    });
    
    function subTotal(){
        var discount = $("input[name='discount']").val();
        var subtotal = $("input[name='totalprice']").val();
        
        subtotal = (1 - (discount / 100)) * subtotal;
        
        $("input#subtotal").autoNumeric('set', subtotal);
        $("input[name='subtotal']").val(subtotal);
        
        return subtotal;
    }
    
    function remaining(){
        var subtotal = $("input[name='subtotal']").val();
        var dept = $("input[name='dept']").val();
        var totalpay = $("input[name='totalpay']").val();
        var refund = $("input[name='refund']").val();
        
        subtotal = parseInt(subtotal);
        dept = parseInt(dept);
        totalpay = parseInt(totalpay);
        refund = parseInt(refund);
        
        var remaining = subtotal + dept - totalpay - refund;
        
        $("input#remaining").autoNumeric('set', remaining);
        $("input[name='remaining']").val(remaining);
    }
    
    $("form#salesinvoice").submit(function(){
        $(rows).each(function(){
            var id = $(this).children("td#total").children("input#id").val();
            var quantity = $(this).children("td#quantity").children("input[name='product[" + id + "][quantity]']").val();
            
            quantity = parseInt(quantity);
            
            if(quantity == 0){
                var row = $(this).closest('tr');
                table.fnDeleteRow(row);
            }
        });
        
        $(".dataTables_filter input").val("");
        
        table.fnFilter('');
        table.fnLengthChange(-1);
    });
    
    var dialog = $("#add-product-form").dialog({
        autoOpen: false,
        height: 450,
        width: 350,
        modal: true,
        buttons: {
            "Thêm": addProduct,
            Cancel: function(){
                dialog.dialog("close");
            }
        },
        close: function(){
            $("form#add-product").trigger("reset");
        }
    });
    
    function addProduct(){
        var brand = $("form#add-product select[name='brand']").val();
        
        if(brand == 0){
            $("#product-error").html("<span>Vui lòng chọn thương hiệu!</span>");
        }else{
            $(".ui-dialog-buttonpane button").attr("disabled", "disabled");
            var price = $("input#newProductPrice").autoNumeric('get');
            $("input#newProductPrice").val(price);
            
            var rs = $("form#add-product").serialize();
            $.ajax({
                url: "<?php echo $this->url(array('controller' => 'product-buy', 'action' => 'create-ajax')); ?>",
                data: {'data': rs},
                success: function(result){
                    $("#product-error").empty();
                    var obj = jQuery.parseJSON(result);
                    
                    $(".ui-dialog-buttonpane button").removeAttr("disabled");
                    
                    if(obj.error == true){
                        $("#product-error").append(obj.message.name);
                        $("#product-error").append(obj.message.net);
                        $("#product-error").append(obj.message.type);
                        $("#product-error").append(obj.message.price);
                    }else{
                        dialog.dialog("close");
                        appendProduct(obj.product);
                    }
                }
            });
        }
    }
    
    function appendProduct(product){
        var id = product.id;
        var name = product.name;
        var price = product.price;
        var discount = 0;
        var discount_type = 1;
        var discount_type_text = "%";
        var quantity = 0;
        var total = 0;
        var net = " ";
        var brand_name = " ";
        var type = " ";
        
        if(product.net != ""){
            net = product.net;
        }
        
        if(product.brand_name != "" && product.brand_name != null){
            brand_name = product.brand_name;
        }
        
        if(product.type != ""){
            type = product.type;
        }
        
        i ++;
        var html = '<tr id="product">';
        
        html += '<td id="stt">';
        html += i;
        html += '</td>';
        
        html += '<td id="name">';
        html += '<input id="checkToDelete" type="checkbox" value="1" name="check"> ';
        html += product.name;
        html += '<br />';
        html += '<a id="deleteForAllCustomer" class="btn btn-mini btn-danger">Xóa tất cả</a> ';
        html += '<a id="deleteForThisCustomer" class="btn btn-mini btn-danger">Xóa</a>';
        html += '</td>';
        
        html += '<td id="net">';
        html += net;
        html += '</td>';
        
        html += '<td id="brand">';
        html += brand_name;
        html += '</td>';
        
        html += '<td id="price">';
        html += '<label id="text_price[' + id + '][price]" style="text-align: left;">' + price + '</label>';
        html += '<br />';
        html += '<input id="price" type="hidden" value="' + price + '" name="product[' + id + '][price]">';
        html += '<a id="changePrice" class="btn btn-mini btn-info">Sửa</a>';
        html += '</td>';
        
        /*html += '<td id="discount">';
        html += '<label id="text_discount[' + id + '][discount]">' + discount + '</label>';
        html += '<br />';
        html += '<a id="changeDiscount" class="btn btn-mini btn-info">Sửa</a>';
        html += '<input id="discount" type="hidden" name="product[' + id + '][discount]" value="' + discount + '">';
        html += '</td>';*/
        
        /*html += '<td id="discount_type">';
        html += '<label id="text_discount_type[' + id + '][discount_type]">' + discount_type_text + '</label>';
        html += '<br />';
        html += '<a id="changeDiscountType" class="btn btn-mini btn-info">Sửa</a>';
        html += '<input id="discount_type" type="hidden" name="product[' + id + '][discount_type]" value="' + discount_type + '">';
        html += '</td>';*/
        
        html += '<td id="quantity">';
        html += '<input id="quantity" class="form-control" type="text" value="0">';
        html += '<input type="hidden" name="product[' + id + '][quantity]" value="0">';
        html += '</td>';
        
        html += '<td id="total">';
        html += '<input id="text_total[' + id + '][total]" class="form-control" type="text" value="0" readonly="">';
        html += '<input id="total" type="hidden" name="product[' + id + '][total]" value="0">';
        html += '<input id="id" type="hidden" value="' + id + '" name="product[' + id + '][id]">';
        html += '<input id="discount" type="hidden" name="product[' + id + '][discount]" value="' + discount + '">';
        html += '<input id="discount_type" type="hidden" name="product[' + id + '][discount_type]" value="' + discount_type + '">';
        html += '</td>';
        
        html += '</tr>';
        
        $(".dataTables_filter input").val("");
        table.fnFilter('');
        
        table.fnAddTr($(html)[0]);
        table.fnPageChange('last');
        
        var row = $("input[name='product[" + id + "][quantity]']").parent("td#quantity").parent("tr#product");
        
        $(row).children("td#quantity").children("input#quantity").autoNumeric('init', optionNumeric1);
        $(row).children("td#price").children("label[id^='text_price']").autoNumeric('init', optionNumeric1);
        $(row).children("td#discount").children("label[id^='text_discount']").autoNumeric('init', optionNumeric1);
        $(row).children("td#total").children("input[id^='text_total']").autoNumeric('init', optionNumeric1);
        
        $(row).children("td#price").children("label[id^='text_price']").autoNumeric('set', price);
        
        $(row).children("td#name").children("a#deleteForAllCustomer").click(function(){
            deleteForAllCustomer(row);
        });
        
        $(row).children("td#name").children("a#deleteForThisCustomer").click(function(){
            deleteForThisCustomer(row);
            
        });
        
        $(row).children("td#price").children("a#changePrice").click(function(){
            changePrice(row);
        });
        
        $(row).children("td#discount").children("a#changeDiscount").click(function(){
            changeDiscount(row);
        });
        
        $(row).children("td#discount_type").children("a#changeDiscountType").click(function(){
            changeDiscountType(row);
        });
        
        $(row).children("td#quantity").children("input#quantity").change(function(){
            var quantity = $(this).autoNumeric('get');
            
            $(this).parent("td#quantity").children("input[name^='product']").val(quantity);
            
            productTotal(row);
        });
    }
    
    $("button#addProduct").click(function(){
        dialog.dialog("open");
    });
    
    function createGotoPage(){
        $("select#gotoPage").empty();
        
        var t = $("#list-group").DataTable();
        var info = t.page.info();
        var pages = info.pages;
        var html = "";
        
        for(var i = 1; i <= pages; i ++){
            html = '<option value="' + i + '">' + (i) + '</option>';
            $("select#gotoPage").append(html);
        }
    }
    
    createGotoPage();
    
    $("select#gotoPage").change(function(){
        var selectPage = $(this).val();
        selectPage = parseInt(selectPage) - 1;
        table.fnPageChange(selectPage);
    });
    
    $("button#cancel").click(function(){
        var url = "<?php echo $this->url(array('module' => 'default', 'controller' => 'sales-invoice', 'action' => 'manage'), null, true); ?>";
        
        location.href = url;
    });
    
    $("button#updateDiscount").click(function(){
        var discount = prompt("Nhập chiếu khấu");
        var i = 0;
        var l = $(rows).length;
        var index = l - 1;
        var lastProduct = $(rows[index]).children("td#total").children("input#id").val();
        
        if(isNaN(discount) && discount.length > 1 || discount < 0){
            alert("Chiếu khấu chỉ được nhập số!");
            return;
        }else{
            if(discount != null && discount >= 0){
                ajaxLoading();
                
                $(rows).each(function(){
                    i ++;
                    
                    var pid = $(this).children("td#total").children("input#id").val();
                    var customer_id = <?php echo $this->customer_id; ?>;
                    var price = $(this).children("td#price").children("input#price").val();
                    var discount_type = 1;
                    var row = $(this);
                    
                    $.ajax({
                        url: "<?php echo $this->url(array('module' => 'default', 'controller' => 'product-price', 'action' => 'update-discount'), null, true); ?>",
                        data: {"pid": pid, 'customer_id': customer_id, 'price': price, 'discount_value': discount},
                        success: function(e){
                            if(e > 0){
                                $(row).children("td#discount").children("label[id^='text_discount']").autoNumeric('set', discount);
                                $(row).children("td#discount").children("input#discount").val(discount);
                                
                                $(row).children("td#discount_type").children("label[id^='text_discount_type']").text('%');
                                $(row).children("td#discount_type").children("input#discount_type").val(1);
                                
                                productTotal(row);
                                
                                if(e == lastProduct){
                                    $("div.imgLoading").remove();
                                }
                            }
                        }
                    });
                });
            }
        }
    });
    
    $("tbody tr").mouseover(function(){
        $(this).addClass("hover");
    });
    
    $("tbody tr").mouseout(function(){
        $(this).removeClass("hover");
    });
});
</script>
<style>
#pageChange{
    margin-top: -20px;
}

#salesinvoice div#headtitle, #salesinvoice div#product{
    padding: 0 0 15px 0;
    border-bottom: 1px solid #DDDDDD;
}

div.imgLoading{
    width: 100%;
    height: 100%;
    top:  0;
    left:  0;
    bottom:  0;
    right:  0;
    background-color: #000000;
    opacity: 0.7;
    position: fixed;
}

img.imgLoading{
    position: fixed;
    top: 50%;
    left: 50%;
    width: 40px;
    height: 40px;
}

div#goSubmit{
    position: fixed;
    bottom: 0px;
    right: 100px;
    padding: 0px 5px;
    background-color: #45484d;
}

div#goSubmit a{
    width: 40px;
    font-size: 30px;
    height: 30px;
    color: #fff;
}

tr#product td{
    font-weight: bold;
    text-transform: capitalize;
}

tbody tr.hover{
    background-color: #D5D5FF !important;
}

tbody tr.hover td{
    font-weight: bold !important;
}
</style>